#include <stdio.h>
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <stdlib.h>
#include <sqlite3.h>


/**
 * sqlite3 回调函数
 */
int sqlite_callback(void *retval, int argc,char **values, char **cols) {
    int i;
    for(i = 0; i < argc; i++) {
        printf("callback %s, %s\n", cols[i], values[i]);
    }
    return 0;
} 

int dictos_find(char *word) {
    int ret;
    sqlite3 *db;
    char *filename;
    char *err;
    char sql[512];

    printf("init db");
    filename = "./dictos.db";
    ret = sqlite3_open(filename, &db);
    if(ret != SQLITE_OK) {
        printf("打开数据库文件失败\n");
        return 1;
    }
    int i;
    FILE *fd;
    char *p;
    sprintf(sql, "select * from dict where word = '%s';", word);
    ret = sqlite3_exec(db, sql, sqlite_callback, NULL, &err);
    if(ret != SQLITE_OK) {
        printf("插入数据失败\n");
    }

    return 0;
}


int dictos_init() {
    int ret;
    sqlite3 *db;
    char *filename;
    char *err;
    char sql[512];

    printf("init db");
    filename = "./dictos.db";
    ret = sqlite3_open(filename, &db);
    if(ret != SQLITE_OK) {
        printf("打开数据库文件失败\n");
        return 1;
    }
    sprintf(sql, "create table if not exists dict (work char[10], mean char[256])");
    ret = sqlite3_exec(db, sql, sqlite_callback, NULL, &err);
    if(ret != SQLITE_OK) {
        printf("创建表失败\n");
        return 1;
    }

    int i;
    FILE *fd;
    char line[512];
    char word[32];
    char mean[256];
    char *p;
    fd = fopen("./dict.txt", "r+");
    if(fd == NULL) {
        perror("打开字典文件失败\n");
        return 1;
    }
    printf("init db");
    while(1) {
        bzero(line, sizeof(line));
        bzero(word, sizeof(word));
        bzero(mean, sizeof(mean));

        if(NULL == fgets(line, sizeof(line), fd)) {
            break;
        }
        //printf("%s\n", line);
        i = 0;
        p = line;
        while(*p != ' ') {
            p++;
            i++;
        }
        strncpy(word, line, i);
        while(*p == ' ') {
            p++;
        }
        //\r\n
        strncpy(mean, p, strlen(p) - 2);
        sprintf(sql, "insert into dict values('%s', '%s');", word, mean);
        printf("%s\n", sql);
        ret = sqlite3_exec(db, sql, sqlite_callback, NULL, &err);
        if(ret != SQLITE_OK) {
            printf("插入数据失败\n");
        }
    }

    return 0;
}

